import { ConfigEnv, UserConfigExport, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import path from 'path'
// 组件命名插件
import vueSetupExtend from 'unplugin-vue-setup-extend-plus/vite'
// svg插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'

// https://vite.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  // 获取各种环境下对应的变量
  let env = loadEnv(mode, process.cwd())
  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      vueSetupExtend({
        enableAutoExpose: true // 是否自动导出
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
      viteMockServe({
        localEnabled: command === 'serve',
      })
    ],
    resolve: { alias: { '@': path.resolve('./src') } }, // 配置别名
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
    build: {
      outDir: "dist",
      // minify: "terser", // esbuild打包速度最快，terser打包体积最小。
      // assetsInlineLimit: 4000, // 小于该值 图片将打包成Base64
      sourcemap: false,
      target: 'esnext',
      cssCodeSplit: true, // 如果设置为false，整个项目中的所有css将会被打包到一个css文件中
      terserOptions: {
    /*    compress: {
          // warnings: false,
          drop_console: true, //打包时删除console
          drop_debugger: true, //打包时删除 debugger
          pure_funcs: ["console.log"]
        },*/
        output: {
          // 去掉注释内容
          comments: true
        }
      },
      reportCompressedSize: false, // 禁用 gzip 压缩大小报告，可略微减少打包时间
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          // js最小拆包
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id.toString().split("node_modules/")[1].split("/")[0].toString();
            }
          },
          // 静态资源分类和包装
          entryFileNames: 'js/[name]-[hash].js',
          chunkFileNames: 'js/[name]-[hash].js',
          assetFileNames(assetInfo) {
            if (assetInfo.name.endsWith('css')) {
              return 'css/[name]-[hash].css';
            }
            const imgExt = ['.png', '.jpeg', '.jpg', '.gif', '.svg', '.webp', '.ico'];
            if (imgExt.some(ext => assetInfo.name.endsWith(ext))) {
              return 'imps/[name]-[hash].[ext]';
            }
            return 'assets/[name]-[hash].[ext]';
          }
        }
      },
    },
    //代理跨域
    server: {
      headers: {
        "Access-Control-Allow-Origin": "*"
      },
      proxy: {
        [env.VITE_APP_BASE_API]: {
          //获取数据的服务器地址设置
          target: env.VITE_SERVE,
          //需要代理跨域
          changeOrigin: true,
          //路径重写
          rewrite: (path) => path.replace(/^\/api/, ''),
        }
      },
      port: 80, // 指定启动端口
      open: true //启动后是否自动打开浏览器
    }
  }
}

